<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>商家登录</p>
    </header>

    <!-- 表单部分 -->
    <ul class="form-box">
      <li>
        <div class="title">手机号码：</div>
        <div class="content">
          <input type="text" v-model="phoneNumber" placeholder="请输入11位手机号码" />
        </div>
      </li>
      <li>
        <div class="title">密码：</div>
        <div class="content">
          <input type="password" v-model="password" placeholder="请输入密码" />
        </div>
      </li>
    </ul>

    <div class="button-login">
      <button @click="login">登录</button>
    </div>
    <div class="button-register">
      <button @click="register">商家注册</button>
    </div>

    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import Footer from "../components/Footer.vue";
import { useRouter } from "vue-router";
import { ref } from "vue";
import { userApi } from "@/api";
import axios from "axios"; // 保留axios导入

// 辅助函数：检查商家是否被删除
const isBusinessDeleted = (business) => {
  // 检查所有可能的删除标记字段
  if (business.deleted === true) return true;
  if (business.isDeleted === true) return true;
  if (business.is_deleted === true) return true;
  if (business.isDeleted === 1) return true;
  if (business.is_deleted === 1) return true;
  
  // 如果没有明确标记为已删除，则认为未删除
  return false;
};

const router = useRouter();

// 使用phoneNumber作为登录标识
const phoneNumber = ref("");
const password = ref("");

const login = async () => {
  if (phoneNumber.value == "") {
    alert("手机号码不能为空！");
    return;
  }
  if (password.value == "") {
    alert("密码不能为空！");
    return;
  }

  try {
    // 使用与用户登录相同的API接口，但提供商家权限的账号
    const response = await userApi.login(phoneNumber.value, password.value);
    
    // 提取JWT token (兼容多种返回格式)
    let jwtToken;
    if (typeof response === 'object' && response !== null) {
        jwtToken = response.id_token || response.token || response.access_token;
    } else if (typeof response === 'string') {
        jwtToken = response;
    }
    
    if (!jwtToken) {
        throw new Error('登录成功但未获取到有效令牌');
    }
    
    localStorage.setItem('jwt-token', jwtToken);
    
    // 获取商家信息
    try {
      // 获取当前用户信息
      const userResponse = await userApi.getCurrentUser();
      
      // 保存用户信息
      localStorage.setItem('user-info', JSON.stringify(userResponse));
      
      // 检查当前用户是否有商家角色
      const isBusiness = userResponse.authorities?.some(auth => 
        auth.name === 'BUSINESS' || auth.name === 'ROLE_BUSINESS'
      );

      if (isBusiness) {
        try {
          console.log("当前登录用户ID:", userResponse.id);
          console.log("当前登录用户名:", userResponse.username);
          
          // 使用新的API端点，直接获取当前用户关联的商家列表
          const response = await axios.get(`/api/businesses/user/${userResponse.id}`);
          
          // 处理响应数据
          let userBusinesses = [];
          if (response && Array.isArray(response)) {
            userBusinesses = response;
          } else if (response && response.data && Array.isArray(response.data)) {
            userBusinesses = response.data;
          } else if (response && response.data && response.data.data && Array.isArray(response.data.data)) {
            // 兼容可能的嵌套数据结构
            userBusinesses = response.data.data;
          }
          
          // 调试：输出第一个商家的完整数据结构
          if (userBusinesses.length > 0) {
            console.log('商家数据结构样例:', JSON.stringify(userBusinesses[0]));
          }
          
          // 过滤掉已删除的商家
          const filteredBusinesses = userBusinesses.filter(business => {
            const isDeleted = isBusinessDeleted(business);
            
            // 如果是被删除的商家，打印信息
            if (isDeleted) {
              console.log(`过滤掉已删除商家: ${business.businessName}, ID: ${business.id}`);
            }
            
            return !isDeleted;
          });
          
          // 更新商家列表
          userBusinesses = filteredBusinesses;
          
          console.log(`过滤后，获取到的商家列表: ${userBusinesses.length}个商家`);
          
          // 调试：输出获取到的商家信息
          userBusinesses.forEach((business, index) => {
            console.log(`商家 ${index+1} - id: ${business.id}, name: ${business.businessName}`);
          });
          
          if (userBusinesses.length > 0) {
            // 将过滤后的商家列表保存到localStorage
            localStorage.setItem("business_stores", JSON.stringify(userBusinesses));
            
            if (userBusinesses.length === 1) {
              // 只有一个商家，直接选择它
              localStorage.setItem("business", JSON.stringify(userBusinesses[0]));
              router.push({ path: '/businessManage' });
            } else {
              // 有多个商家，跳转到店铺选择页面
              console.log(`跳转到店铺选择页面，共有${userBusinesses.length}个商家...`);
              router.push({ path: '/businessStoreSelector' });
            }
          } else {
            alert("未找到与您账号关联的商家！请先注册商家或联系管理员。");
          }
        } catch (error) {
          console.error("获取商家信息出错:", error);
          alert("获取商家信息失败，请重新登录");
        }
      } else {
        alert("该账号没有商家权限！");
      }
    } catch (error) {
      console.error("获取用户信息出错:", error);
      alert("登录失败，无法获取用户信息");
    }
  } catch (error) {
    console.error("商家登录请求出错:", error);
    alert(error.message || "账号或密码错误，请重新输入");
  }
};

const register = () => {
  router.push({ path: "/businessRegister" });
};
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;

  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;

  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 表单部分 ******************/
.wrapper .form-box {
  width: 100%;
  margin-top: 12vw;
}

.wrapper .form-box li {
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
  display: flex;
  align-items: center;
}

.wrapper .form-box li .title {
  flex: 0 0 18vw;
  font-size: 3vw;
  font-weight: 700;
  color: #666;
}

.wrapper .form-box li .content {
  flex: 1;
}

.wrapper .form-box li .content input {
  border: none;
  outline: none;
  width: 100%;
  height: 4vw;
  font-size: 3vw;
}

.wrapper .button-login {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}

.wrapper .button-login button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #fff;
  background-color: #38ca73;
  border-radius: 4px;

  border: none;
  outline: none;
}

.wrapper .button-register {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}

.wrapper .button-register button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #fff;
  background-color: #0097ff;
  border-radius: 4px;

  border: none;
  outline: none;
}
</style> 